package com.leetcode.Offer;

public class JZ67 {
    public int strToInt(String str) {
        //判断能不能转换
        if (str == null || str.length() == 0) {
            return 0;
        }
        String trim = str.trim();
        if (trim == null || trim.length() == 0) {
            return 0;
        }
        char[] chars = trim.toCharArray();
        StringBuilder builder = new StringBuilder();
        long num = 0;
        if (Character.isDigit(chars[0])) {//第一个字符是数字
            for (int i = 0; i < chars.length && Character.isDigit(chars[i]); i++) {
                num = num * 10 + (chars[i] - '0');
                if (num > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
            }
        } else if (chars[0] == '-') {
            for (int i = 1; i < chars.length && Character.isDigit(chars[i]); i++) {
                num = num * 10 + (chars[i] - '0');
                if (num > Integer.MAX_VALUE) {
                    return Integer.MIN_VALUE;
                }
            }
            num = num * (-1);
        } else if (chars[0] == '+') {
            for (int i = 1; i < chars.length && Character.isDigit(chars[i]); i++) {
                num = num * 10 + (chars[i] - '0');
            }
        } else {
            return 0;
        }
        //用long记录
        if (num < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        } else if (num > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else {
            return (int) num;
        }

    }


    public static void main(String[] args) {
        System.out.println(new JZ67().strToInt("-91283472332"));
    }
}
